package com.zh.kotlin_mvvm.ui

import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MotionEvent
import com.zh.common.base.BaseActivity
import com.zh.kotlin_mvvm.R
import com.zh.kotlin_mvvm.databinding.ActivityAudioBinding
import com.zh.kotlin_mvvm.voice.AudioRecordPlayManager
import com.zh.kotlin_mvvm.voice.VoiceMsg

class AudioActivity : BaseActivity<ActivityAudioBinding>() {

    private var filePath = ""

    @SuppressLint("ClickableViewAccessibility")
    override fun initView(savedInstanceState: Bundle?) {

        viewBinding.btRecord.setOnFinishedRecordListener { audioPath, time ->
            val msg = VoiceMsg(audioPath, time, System.currentTimeMillis())
            filePath = audioPath
            viewBinding.addr.text = "地址：$audioPath"
        }

        viewBinding.btLongRecord.setOnTouchListener { v, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    AudioRecordPlayManager.getInstance().startRecord(this) {
                        filePath = it
                        viewBinding.addr.text = "地址：$it"
                    }
                }

                MotionEvent.ACTION_UP -> {
                    AudioRecordPlayManager.getInstance().stopRecord()
                }
            }
            false
        }

        viewBinding.btPlay.setOnClickListener {
            AudioRecordPlayManager.getInstance().playAudio(this, filePath)
//            AudioRecordPlayManager.getInstance().playAudio(this, "https://378-ssltxt.jieershunqingjie.com/klajdfiaoj/music_collect/3753/20AB64C9954080EB622C6DF5095F4384/20AB64C9954080EB622C6DF5095F4384_9_m.m4a")
        }
    }

    override fun onPause() {
        AudioRecordPlayManager.getInstance().pausePlayAudio()
        super.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        AudioRecordPlayManager.getInstance().stopRecord()
        AudioRecordPlayManager.getInstance().stopPlayAudio()
    }
}
